export class Context<T> {
  private data: T;
  private listeners: Array<(newValue: T) => void> = [];

  constructor(initialValue: T) {
    this.data = initialValue;
  }

  getData(): T {
    return this.data;
  }

  setData(newValue: T): void {
    this.data = newValue;
    this.notifyListeners();
  }

  subscribe(listener: (newValue: T) => void): () => void {
    this.listeners.push(listener);
    return () => {
      this.listeners = this.listeners.filter((l) => l !== listener);
    };
  }

  private notifyListeners(): void {
    this.listeners.forEach((listener) => listener(this.data));
  }
}
